package com.witdata.security.config;

import com.witdata.security.auth.MyAccessDeniedHandler;
import com.witdata.security.auth.MyAuthenticationEntryPoint;
import com.witdata.security.filter.JwtAuthenticationFilter;
import com.witdata.security.filter.PermissionFilter;
import com.witdata.security.service.impl.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfiguration {
    private final UserDetailsServiceImpl userDetailsService;
    private final IgnoreUrlsConfiguration ignoreUrlsConfiguration;
    private final MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    private final MyAccessDeniedHandler myAccessDeniedHandler;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final PermissionFilter permissionFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        List<String> ignoreUrls = ignoreUrlsConfiguration.getIgnoreUrls();
        http.authorizeHttpRequests(auth -> {
            if (ignoreUrls != null) {
                for(String url : ignoreUrls){
                    auth.requestMatchers(url).permitAll();
                }
                System.out.println("ignoreUrls = " + ignoreUrls);
            }
            // 对于其他路径，则需要进行认证
            auth.anyRequest().authenticated();
        });
        http.userDetailsService(userDetailsService);
        // 因为不需要session，所以关闭csrf
        http.csrf(AbstractHttpConfigurer::disable);
        // 默认跨域
        http.cors(Customizer.withDefaults());
        // 定义异常处理
        http.exceptionHandling(e -> {
            e.authenticationEntryPoint(myAuthenticationEntryPoint);
            e.accessDeniedHandler(myAccessDeniedHandler);
        });
        // 添加JWT认证过滤器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加权限过滤器
        http.addFilterBefore(permissionFilter, AuthorizationFilter.class);
        return http.build();
    }

}
